<?php

namespace app\index\controller;

use app\common\controller\Log;
use app\common\model\Member;
use app\common\model\MemberFinance;
use app\common\model\TradersOrder as TradersOrderModel;
use think\Db;
use app\common\model\Traders as tradersModel;

class TradersOrder extends Home
{
    private $status_arr = [
        0 => '待付款',
        10 => '已付款',
        15 => '申诉中',
        20 => '已完成',
    ];
    private $paytype_arr = [
        1 => '银行卡',
        2 => '支付宝',
        3 => '微信',
    ];
    protected $beforeActionList = [
        'check_load',
    ];

    /**
     * 订单列表// 0未付款10已付款15申诉未转币20完成
     */
    public function lists()
    {
        $page = input('page');
        $start = ($page - 1) * self::$totalList;

        $uid = $this->uid;
        $status = input('status', 0);
        $recordtype = input('recordtype', 0);

        $map = [
            'recordtype' => $recordtype,
            'status' => $status
        ];

        $role = input('role', 1);
        if ($role == 1) {
            $map['uid'] = $uid;
        } elseif ($role == 2) {
            $traderId = \app\common\model\Traders::where('uid', $uid)->value('id');
            $map['trader_id'] = $traderId;
        }

        $lists = TradersOrderModel::where($map)
            ->order('update_time desc')
            ->limit($start, self::$totalList)
            ->select();

        $totalCount = TradersOrderModel::where($map)
            ->count();

        if ($totalCount > 0) {
            foreach ($lists as $v) {
                if ($role == 1) {
                    $traderInfo = \app\common\model\Traders::find($v->trader_id);
                    $v->avatar = $traderInfo->avatar > 0 ? get_cover($traderInfo->avatar, 'path') : '';
                    $v->trader_name = $traderInfo->name;
                    $v->paytype_name = $this->paytype_arr[$v->paytype];
                } else {
                    $memberInfo = Member::find($v->uid);
                    $v->avatar = $memberInfo->icon;
                    $v->realname = $memberInfo->realname;
                    $v->paytype_name = $this->paytype_arr[$v->paytype];
                }
            }
        }

        $this->apiSuccess('交易列表', ['list' => $lists, 'totalCount' => $totalCount]);
    }

    /**
     * 新建交易订单
     */
    public function add()
    {
        $uid = $this->uid;
        $memberModel = Member::find($uid);

        $data = input('post.');

        $res = $this->checkCode($memberModel->mobile, $data['code']);
        if ($res['status'] == 0) {
            $this->apiError($res['msg']);
        }
        $traderInfo = tradersModel::find($data['id']);

        if (!$traderInfo) {
            $this->apiError('商家不存在！');
        }

        if ($traderInfo->uid == $uid) {
            $this->apiError('不能自己和自己交易！');
        }

        $tradersOrderModel = new TradersOrderModel();

        $num = $data['money'];
        if ($data['recordtype'] == 1) {
            // 会员买入
            $total = $data['money'];
            if ($traderInfo->hasmoney < $num) {
                $this->apiError('商家余额不足！');
            }

            $tradersOrderModel->price = 1;
            $tradersOrderModel->paytype = -1;

            $touid = $traderInfo->uid;
        } else {
            // 会员售出
            $total = round($num * $traderInfo->price, 4);
            if ($data['type'] == 1) {
                $total = $data['money'];
                $num = round($data['money'] / $traderInfo->price, 4);
            }

            $memberFinanceModel = MemberFinance::where('uid', $uid)->find();
            if ($memberFinanceModel->haswealth < $num) {
                $this->apiError('账户余额不足！');
            }

            $tradersOrderModel->price = $traderInfo->price;
            $tradersOrderModel->paytype = $data['paytype'];

            $touid = $uid;
        }

        if ($num < $traderInfo['min_total']) {
            $this->apiError('不能低于最低限量！');
        }

        if ($num > $traderInfo['max_total']) {
            $this->apiError('不能高于最高限量！');
        }

        $tradersOrderModel->order_number = create_order($uid);
        $tradersOrderModel->trader_id = $data['id'];
        $tradersOrderModel->recordtype = $data['recordtype'];
        $tradersOrderModel->num = $num;
        $tradersOrderModel->total = $total;
        $tradersOrderModel->uid = $uid;

        $remark = '';
        Db::startTrans();
        try {

            if ($data['recordtype'] == 1) {
                $traderInfo->hasmoney -= $num;
                $hasmoney = $traderInfo->hasmoney;
                $traderInfo->save();
                $remark = 'trader';
            } else {
                $memberFinanceModel->haswealth -= $num;
                $hasmoney = $memberFinanceModel->haswealth;
                $memberFinanceModel->save();
            }

            $tradersOrderModel->save();

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->apiError('扣费失败！');
        }

        $type = array('recordtype' => 0, 'changetype' => 28, 'moneytype' => 3);
        $money = array('money' => $num, 'hasmoney' => $hasmoney);
        money_change($type, $touid, $touid, $money, '', $remark);
        unset($type, $money);

        $this->destroyCode($memberModel->mobile);

        $content = '尊敬的市商：您好，有会员在 ' . date('Y-m-d H:i', time()) . ' 跟你发起交易，请进入app及时处理！！！【鸿铭优选】';
//        Log::insertLog($traderInfo->mobile);
        $res = $this->sendMsg($traderInfo->mobile, $content);
        Log::insertLog('短信结果：' . json_encode($res));

        $this->apiSuccess('订单已提交');
    }

    /**
     * 订单详情
     */
    public function one()
    {
        $data = input('post.');
        $id = $data['id'];
        $tradersOrderModel = TradersOrderModel::find($id);
        if ($tradersOrderModel->id <= 0) {
            $this->apiError('该订单不存在！');
        }
        $tradersOrderModel->status_name = $this->status_arr[$tradersOrderModel->status];
        $tradersOrderModel->paytype_name = $this->paytype_arr[$tradersOrderModel->paytype];

        $tInfo = \app\common\model\Traders::find($tradersOrderModel->trader_id);

        $tradersOrderModel->realname = $tInfo->realname;
        $tradersOrderModel->bank_name = $tInfo->bank_name;
        $tradersOrderModel->bank_number = $tInfo->bank_number;
        $tradersOrderModel->alipay_account = $tInfo->alipay_account;
        $tradersOrderModel->wechat_account = $tInfo->wechat_account;
        $this->apiSuccess('订单详情', $tradersOrderModel);
    }

    /**
     * 确认打款
     */
    public function confirmPay()
    {
        $data = input('post.');
        if (!$data['icon']) {
            $this->apiError('打款截图缺失！');
        }
        $id = $data['id'];
        $tradersOrderModel = TradersOrderModel::find($id);
        if ($tradersOrderModel->id <= 0) {
            $this->apiError('该订单不存在！');
        }

        if ($tradersOrderModel->status != 0) {
            $this->apiError('该订单暂时不可打款！');
        }

        $tradersOrderModel->icon = $data['icon'];
        $tradersOrderModel->pay_time = time();
        $tradersOrderModel->status = 10;

        $res = $tradersOrderModel->save();
        if ($res) {
            $this->apiSuccess('打款成功！');
        } else {
            $this->apiError('打款失败！');
        }
    }

    /**
     * 申诉
     */
    public function complain()
    {
        $data = input('post.');
        $id = $data['id'];
        $tradersOrderModel = TradersOrderModel::find($id);
        if ($tradersOrderModel->id <= 0) {
            $this->apiError('该订单不存在！');
        }

        if ($tradersOrderModel->status == 15) {
            $this->apiError('该订单已申诉！');
        }

        if ($tradersOrderModel->status == 20) {
            $this->apiError('该订单已完成！');
        }

        $tradersOrderModel->status = 15;

        $res = $tradersOrderModel->save();
        if ($res) {
            $this->apiSuccess('申诉成功！');
        } else {
            $this->apiError('申诉失败！');
        }
    }

    /**
     * 确认订单
     */
    public function confirmOrder()
    {
        $data = input('post.');
        $id = $data['id'];
        $tradersOrderModel = TradersOrderModel::find($id);
        if ($tradersOrderModel->id <= 0) {
            $this->apiError('该订单不存在！');
        }

        if (!in_array($tradersOrderModel->status, [10, 15])) {
            $this->apiError('该订单暂时不可确认！');
        }

        $tradersOrderModel->finish_time = time();
        $tradersOrderModel->status = 20;

        $traderModel = \app\common\model\Traders::find($tradersOrderModel->trader_id);
        $remark = '';

        Db::startTrans();
        try {
            $tradersOrderModel->save();
            if ($tradersOrderModel->recordtype == 1) {
                // 会员买入
                $memberModel = MemberFinance::where('uid', $tradersOrderModel->uid)->find();
                $memberModel->haswealth += $tradersOrderModel->num;
                $memberModel->allwealth += $tradersOrderModel->num;
                $memberModel->save();

                $hasmoney = $memberModel->haswealth;
                $uid = $tradersOrderModel->uid;
            } else {
                // 会员售出
                $traderModel->hasmoney += $tradersOrderModel->num;
                $traderModel->totalmoney += $tradersOrderModel->num;
                $traderModel->save();

                $hasmoney = $traderModel->hasmoney;
                $uid = $traderModel->uid;
                $remark = 'trader';
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->apiError('确认失败！');
        }

        $type = array('recordtype' => 1, 'changetype' => 37, 'moneytype' => 3);
        $money = array('money' => $tradersOrderModel->num, 'hasmoney' => $hasmoney);
        money_change($type, $uid, $uid, $money, '', $remark);
        unset($type, $money);

        tradersModel::where('id', $tradersOrderModel->trader_id)->setInc('today_num');
        tradersModel::where('id', $tradersOrderModel->trader_id)->setInc('total_num');
        $this->apiSuccess('确认成功！');
    }
}